package malagaAcoge.controller.beans;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;

import malagaAcoge.utils.Messages;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;

public class DocumentosBean {
	private TreeNode seleccionado;
	private TreeNode root;
	private HashMap<String, String> rutas;
	private String cadena;

	public DocumentosBean() {
		rutas = new HashMap<String, String>();
		root = new DefaultTreeNode("Root", null);
		TreeNode demandas = new DefaultTreeNode("Demandas", root);
		TreeNode informes = new DefaultTreeNode("Informes", root);
		TreeNode intervenciones = new DefaultTreeNode("Intervenciones", root);
		TreeNode itinerarios = new DefaultTreeNode("Itinerarios", root);
		File dir = new File(Messages.getString("DemandasBean.directorio"));
		String[] ficheros = dir.list();
		if (ficheros != null) {
			for (int i = 0; i < ficheros.length; i++) {
				TreeNode child = new DefaultTreeNode(ficheros[i], demandas);
				File dir1 = new File(
						Messages.getString("DemandasBean.directorio")
								+ ficheros[i]);
				String[] ficheros1 = dir1.list();
				if (ficheros1 != null) {
					for (int j = 0; j < ficheros1.length; j++) {
						TreeNode child2 = new DefaultTreeNode("document",ficheros1[j],child);
						rutas.put(ficheros1[j],
								Messages.getString("DemandasBean.directorio")
										+ ficheros[i] + "\\" + ficheros1[i]);
					}
				}

			}
		}
		dir = new File(Messages.getString("IntervencionsBean.directorio"));
		ficheros = dir.list();
		if (ficheros != null) {
			for (int i = 0; i < ficheros.length; i++) {
				TreeNode child = new DefaultTreeNode(ficheros[i], intervenciones);
				File dir1 = new File(
						Messages.getString("IntervencionsBean.directorio")
								+ ficheros[i]);
				String[] ficheros1 = dir1.list();
				if (ficheros1 != null) {
					for (int j = 0; j < ficheros1.length; j++) {
						TreeNode child2 = new DefaultTreeNode("document",
								ficheros1[j],child);
						rutas.put(
								ficheros1[j],
								Messages.getString("IntervencionsBean.directorio")
										+ ficheros[i] + "\\" + ficheros1[i]);

					}
				}

			}
		}
		dir = new File(Messages.getString("InformesBean.directorio"));
		ficheros = dir.list();
		if (ficheros != null) {
			for (int i = 0; i < ficheros.length; i++) {
				TreeNode child = new DefaultTreeNode("document",ficheros[i], informes);
				rutas.put(ficheros[i],
						Messages.getString("InformesBean.directorio")
								+ ficheros[i]);
			}
		}
		dir = new File(Messages.getString("UsuariosBean.directorio"));
		ficheros = dir.list();
		if (ficheros != null) {
			for (int i = 0; i < ficheros.length; i++) {
				TreeNode child = new DefaultTreeNode("document",ficheros[i], itinerarios);
				rutas.put(ficheros[i],
						Messages.getString("UsuariosBean.directorio")
								+ ficheros[i]);
			}
		}

	}

	public void setRoot(TreeNode root) {
		this.root = root;
	}
	public void buscar(){
		buscar(root,cadena);
	}
	private void buscar(TreeNode root2, String cadena2) {
		if (root2.getChildren()!=null && !root2.getChildren().isEmpty()){
			for (TreeNode child:root2.getChildren()){
				buscar(child,cadena2);
			}
		}else{
			if (root2.getData().toString().toUpperCase().contains(cadena2.toUpperCase())){
				expand(root2);
				root2.setSelected(true);
			}
		}
	}
	private void expand (TreeNode root2) {
		root2.setExpanded(true);
		TreeNode parent = root2.getParent();
		if(parent!=null){
			parent.setExpanded(true);
			expand(parent);
		}
		
	}

	public void descargar() {
		if (seleccionado != null) {
			String nombre = seleccionado.getData().toString();
			String path = rutas.get(nombre);
			if (path != null && path != "") {
				File file = new File(path);
				if (file.exists()) {
					try {
						FacesContext facesContext = FacesContext
								.getCurrentInstance();
						HttpServletResponse response = (HttpServletResponse) facesContext
								.getExternalContext().getResponse();
						String contentDispositionValue = "attachment";
						if (nombre.contains(".doc") || nombre.contains(".docx")) {
							response.setContentType("application/msword");
						} else {
							response.setContentType("application/octet-strem");
						}
						response.setHeader("Content-Disposition",
								contentDispositionValue + ";filename=\""
										+ nombre + "\"");
						byte[] buffer = new byte[2048];
						int length;
						InputStream inputStream = new FileInputStream(file);
						OutputStream outputStream = response.getOutputStream();

						while ((length = (inputStream.read(buffer))) != -1) {
							outputStream.write(buffer, 0, length);
						}

						response.setStatus(200);

						response.getOutputStream().flush();
						inputStream.close();
						facesContext.responseComplete();

					} catch (IOException e) {
						System.out.println("Error al descargar el archivo: "
								+ path);
					}
				}
			}
		}
	}

	public TreeNode getRoot() {

		return root;
	}

	public void setSeleccionado(TreeNode seleccionado) {
		this.seleccionado = seleccionado;
	}

	public TreeNode getSeleccionado() {
		return seleccionado;
	}

	public void setCadena(String cadena) {
		this.cadena = cadena;
	}

	public String getCadena() {
		return cadena;
	}

}
